package com.xuan.api.sms.controller;

import com.xuan.constant.MQConstant;
import com.xuan.model.respons.ResultBody;
import com.xuan.utils.CommonUtils;
import com.xuan.utils.PhoneUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class SmsController {


    @Autowired
    private RabbitTemplate rabbitTemplate;


    @GetMapping("/sms/sendSms/{mobile}")
    public ResultBody sendSms(@PathVariable("mobile") String mobile){
        if (PhoneUtils.isChinaPhoneLegal(mobile)){//判断手机号是否合格
            try {
                //生成验证码
                String code = CommonUtils.generateCode();
                Map<String,Object> map =  new HashMap<>();
                map.put("code",code);
                map.put("mobile",mobile);
                rabbitTemplate.convertAndSend(MQConstant.SEND_SMS_DIRECT_EXCHANGE,MQConstant.SEND_SMS_KEY_BINDING,map);
                log.info("手机号为===="+mobile+";;;验证码为====="+code);
                return new ResultBody<String>().OK("发送成功").data(code);
            } catch (AmqpException e) {
                e.printStackTrace();
                return new ResultBody().Fail("信息发送失败");
            }
        }
        return new ResultBody().Fail("手机号不正确");
    }
}
